package com.example.demo.controller;

import com.example.demo.Response;
import com.example.demo.dto.ClothDTO;
import com.example.demo.dto.UserDetailDTO;
import com.example.demo.service.FileService;
import com.example.demo.service.UserDetailService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class UserDetailController {
    @Autowired
    FileService fileService;

    @Autowired
    private UserDetailService userDetailService;

    @GetMapping("/userdetail/{userId}")
    public Response<UserDetailDTO> getUserDetailByUserId(@PathVariable long userId) {
        return Response.newSuccess(userDetailService.getUserDetailByUserId(userId));
    }

    @PostMapping("/userdetail/{userId}")
    public Response<Long> addUserDetailByUserId(@PathVariable long userId, @RequestBody UserDetailDTO userDetailDTO) {
        return Response.newSuccess(userDetailService.addNewUserDetailByUserId(userId, userDetailDTO));
    }

    @DeleteMapping("/userdetail/{userId}")
    public void deleteUserDetailByUserId(@PathVariable long userId) {
        userDetailService.deleteUserDetailByUserId(userId);
    }

    @PutMapping("/userdetail/{userId}")
    public Response<UserDetailDTO> updateUserDetailByUserId(
            @PathVariable long userId,
            @RequestParam(required = false) String bio,
            @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
            @RequestParam(required = false) Long followersCount,
            @RequestParam(required = false) Integer followingCount,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String birthday,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String school) {
        try {
            String imageName = "";
            if (imageFile != null) {
                imageName = fileService.storeFile(imageFile);
            }
            if (followersCount == null) {
                followersCount = 0L;
            }
            if (followingCount == null) {
                followingCount = 0;
            }

            return Response.newSuccess(userDetailService.updateUserDetailByUserId(
                    userId,
                    imageName,
                    bio,
                    followersCount,
                    followingCount,
                    gender,
                    birthday,
                    location,
                    school));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

